<?php
class UserLocationDABase extends AbstractDbObject {
    /**
     * Table name
     *
     * @var string
     */
    protected $tableName = 'user_location';

    /**
     * Table alias
     *
     * @var string
     */
    protected $tableAlias = 'user_location';

    /**
     * Create a page
     *
     * @access public
     *
     * @param UserLocationEntity $userLocationEntity: object
     *
     * @return primary key has just been inserted
     */
    public function create($userLocationEntity) {
        try {
            // Get db object
            $dbWriter = $this->getDbWriter();

            // Fetch array
            $data = array (
                    'city_id' => $userLocationEntity->city_id,
                    'number' => $userLocationEntity->number,
                    'street' =>$userLocationEntity->street,
                    'ward' => $userLocationEntity->ward,
                    'ngo' => $userLocationEntity->ngo,
                    'district_id' => $userLocationEntity->district_id,
                    'guide' => $userLocationEntity->guide,
                    'default' => $userLocationEntity->default,
            );

            // Insert into database
            $dbWriter->insert($this->tableName, $data);

            // Return primary key has just created
            return $dbWriter->lastInsertId($this->tableName, 'id');
        }
        catch (Exception $ex) {


            throw $ex;
        }
    }

    /**
     * Update a userLocation
     *
     * @access public
     *
     * @param UserLocationEntity $userLocationEntity: object
     *
     * @return bool true if update success otherwise return false
     */
    public function update($userLocationEntity) {
        try {
            // Get db object
            $dbWriter = $this->getDbWriter();

            //echo $userLocationEntity->picture;
            //die();

            // Fetch array
            $data = array (
                    'city_id' => $userLocationEntity->city_id,
                    'number' => $userLocationEntity->number,
                    'street' =>$userLocationEntity->street,
                    'ward' => $userLocationEntity->ward,
                    'ngo' => $userLocationEntity->ngo,
                    'district_id' => $userLocationEntity->district_id,
                    'guide' => $userLocationEntity->guide,
                    'default' => $userLocationEntity->default,
            );

            // Update userLocation
            $idQoute = $dbWriter->quote($userLocationEntity->id);
            $where[] = "id = $idQoute";

            // Execute query
            $numRows = $dbWriter->update($this->tableName, $data, $where);
            if ($numRows > 0) {
                return true;
            }
            else {
                return false;
            }
        }
        catch (Exception $ex) {
            throw $ex;
        }
    }

    /**
     * Delete a userLocation by Id
     *
     * @access public
     *
     * @param int $id: Id of userLocation
     *
     * @return bool whether delete action is success or not
     */
    public function del($id) {
        try {
            // Get db object
            $dbWriter = $this->getDbWriter();

            // Update userLocation
            $idQuote = $dbWriter->quote($id);

            // Execute query
            $rowCount = $dbWriter->delete($this->tableName, "id = $idQuote");

            // Return boolean result
            if ($rowCount > 0) {
                return true;
            }
            else {
                return false;
            }
        }
        catch (Exception $ex) {
            throw $ex;
        }
    }

    /**
     * Get UserLocationEntity object by Id of the userLocation
     *
     * @access public
     *
     * @param int $id: Id of userLocation
     *
     * @return UserLocationEntity object
     */
    public function getById($id) {
        // Get db object
        $dbWriter = $this->getDbWriter();

        // Add quote
        $idQuote = $dbWriter->quote($id);

        // Query for get userLocation by Id
        $query = "
			SELECT {$this->tableName}.*
			FROM {$this->tableName}
			WHERE {$this->tableName}.id = $idQuote
                ";
        $result = $dbWriter->fetchRow($query);
        if (is_null($result) || !is_array($result)) {

            // Id of the userLocation does not exist
            return null;
        }
        $userLocationEntity = new UserLocationEntity($result);

        // Return UserLocationEntity object
        return $userLocationEntity;
    }

    public function getBuyUserAndCity($user_id, $city_id, $default = false) {
        // Get db object
        $dbWriter = $this->getDbWriter();

        // Query for get userLocation by Id
        $query = "SELECT {$this->tableName}.*
			FROM {$this->tableName}
			WHERE {$this->tableName}.user_id = ". $user_id ." 
			AND {$this->tableName}.city_id = ". $city_id;
        if($default){
        	$query .=" AND `default` = 1";
        }
        $result = $dbWriter->fetchRow($query);
        if (is_null($result) || !is_array($result)) {

            // Id of the userLocation does not exist
            return null;
        }
        $userLocationEntity = new UserLocationEntity($result);

        // Return UserLocationEntity object
        return $userLocationEntity;
    }
    
    /**
     * Get all rows of userLocation table with search criterias
     *
     * @access public
     *
     * @param array $arrElement: array of search criterias
     * @param string $orderBy: Field and the way ordered (ASC or DESC)
     * @param int $begin: Begin item
     * @param int $limit: Number rows to query
     * @param string $where: added where string
     *
     * @return array of userLocationEntity object
     */
    public function getItems($arrElement, $orderBy = null, $begin = null, $limit = null, $where = null, $having = null) {
        // Get db object
        $dbWriter = $this->getDbWriter();

        // Query for get all items of user deposit with search criterias
        $query = "
			SELECT {$this->tableName}.*
			FROM {$this->tableName} ";

        // Add where
        $whereTmp = "";
        $whereClause = $this->buildWhereClause($arrElement, $dbWriter, $this->tableName);
        $concat = !empty($whereClause) && !empty($whereTmp) ? ' AND ' : '';
        if (empty($whereClause) && !empty($whereTmp)) {
            $whereClause = ' WHERE ';
        }
        $query .= " {$whereClause}{$concat}{$whereTmp} ";

        if (!empty($where)) {
            $query .= " AND " . $where;
        }

        if (!empty($having)) {
            $query .= " HAVING " . $having;
        }

        // Add order By
        $query .= $this->buildOrderClause($orderBy);

        // Add begin and Limit
        $query .= $this->buildLimitClause($begin, $limit);

        // Execute query
        $result = $dbWriter->fetchAll($query);

        $buffer = null;
        foreach ($result as $element) {
            $userLocationEntity = new UserLocationEntity($element);

            // Add UserLocationEntity into result
            $buffer[] = $userLocationEntity;
        }
        return $buffer;
    }

    /**
     * Get total rows of userLocation
     *
     * @access public
     *
     * @param array $arrElement: array of search criterias
     *
     * @return int total: total rows of userLocation
     */
    public function getTotals($arrElement) {
        // Get db object
        $dbWriter = $this->getDbWriter();

        // Query for get total records in userLocation table
        $query = "
			SELECT COUNT(*) as total
			FROM {$this->tableName} ";
        // Add where
        $query .= $this->buildWhereClause($arrElement, $dbWriter);

        // Execute query
        $result = $dbWriter->fetchRow($query);

        if (!is_null($result)) {
            return (int) $result['total'];
        }

        // Return no record
        return 0;
    }
}